<template>
  <div class="newsList">
    <search-block type="flex">
      <template slot="button">
        <el-button type="primary" @click="search(true)">查询</el-button>
        <el-button type="primary" @click="addNews">添加新闻</el-button>
      </template>
      <el-form inline :model="model">
        <el-form-item label="标题:">
          <el-input v-model="model.title" clearable></el-input>
        </el-form-item>
        <el-form-item label="作者:">
          <el-input v-model="model.author" clearable></el-input>
        </el-form-item>
        <el-form-item label="发布时间:">
          <el-date-picker
            v-model="model.publishDate"
            clearable
            type="date"
            value-format="yyyy-MM-dd"
            :picker-options="{
              shortcuts: [{
              text: '今天',
              onClick(picker) {
                picker.$emit('pick', new Date());
                }
              }]
            }"></el-date-picker>
        </el-form-item>
      </el-form>
    </search-block>
    <y-table
        ref="table"
        border
        pagination
        :getDataWay="getDataWay"
        :columns="columns"
    >
      <el-table-column slot="publishStatus" label="发布" align="center" header-align="center">
        <template v-slot="scope">
          <el-popconfirm
              :title="scope.row.publishStatus === 0 ? '是否确认发布该新闻？' : '是否确认取消发布该新闻？'"
              @confirm="() => {
            if(scope.row.publishStatus === 0) post(scope.row)
            else unPost(scope.row);
          }"
          >
            <el-switch
                disabled
                slot="reference"
                v-model="scope.row.publishStatus"
                :active-value="1"
                :inactive-value="0"></el-switch>
          </el-popconfirm>
        </template>
      </el-table-column>
      <el-table-column slot="y-oper" label="操作" align="center" header-align="center" width="210">
        <template v-slot="scope">
          <div class="table-buttons">
            <el-button size="mini" @click="showDetails(scope.row)">预览</el-button>
            <el-button type="primary" size="mini" @click="editNews(scope.row)" v-if="scope.row.publishStatus === 0">编辑</el-button>
            <el-button size="mini" @click="viewNews(scope.row)" v-if="scope.row.publishStatus === 1">查看</el-button>
            <el-popconfirm
                title="是否确认删除该新闻？"
                @confirm="delNews(scope.row)">
              <el-button slot="reference" type="danger" size="mini">删除</el-button>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </y-table>
    <y-form
      ref="yForm"
      v-model="forms.formModel"
      :visible.sync="forms.showForm"
      :title="forms.formTypeTitle[forms.formsType]"
      :disabled="forms.formsType === 'VIEW'"
      :show-button="forms.formsType !== 'VIEW'"
      destroy-on-close
      width="900px"
      force-inner-scroll
      :form-attrs="forms.formAttrs"
      :columns="formColumns"
      @ensure="ensureModel">
    </y-form>
    <el-dialog
      :visible.sync="watchDetails.show"
      title="详情预览">
      <div class="ql-editor" v-html="watchDetails.content"></div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "newsList",
  inject: ['getDictNameSync'],
  computed:{
    getDataWay(){
      return{
        dataType: 'url',
        data: this.$api.applet.newsList,
        param: this.model
      }
    },
    formColumns(){
      return [
        {
          label: "标题",
          prop: "title",
          comp:{
            compType: 'input',
            attrs:{
              maxlength: 30,
              showWordLimit: true
            }
          }
        },{
          label: "作者",
          prop: "author",
          comp:{
            compType: 'input',
            attrs:{
              maxlength: 30,
              showWordLimit: true
            }
          }
        },{
          label: "缩略图片",
          prop: "coverPage",
          comp:{
            compType: 'YUploadImg',
            attrs:{
              url: this.forms.formModel.coverPage ? [{
                url: this.forms.formModel.coverPage,
                id: this.forms.formModel.attachmentId
              }] : [],
              valueType: "ObjectArray",
              businessSysModuleCode: "ENTERPRISE_NEWS",
              limit: 1,
              reUpload: true,
              cropperOptions:{
                fixedNumber: [25, 12]
              }
            },
            listeners:{
              update: this.updateModel
            }
          }
        },{
          label: "标签",
          prop: "label",
          comp:{
            compType: 'YDynamicTags',
            attrs:{
              tips: '添加标签',
              disabled: this.forms.formsType === 'VIEW'
            }
          }
        },{
          label: "新闻正文",
          prop: "content",
          comp:{
            compType: 'YRichText',
            attrs:{
              businessSysModuleCode: 'NEWS',
              disabled: this.forms.formsType === 'VIEW',
              video: true
            }
          }
        }
      ]
    }
  },
  data(){
    return{
      model:{
        publishDate: '',
        title: '',
        author: ''
      },
      columns: [{
        label: "标题",
        prop: "title"
      },{
        label: "作者",
        prop: "author"
      },{
        label: "标签",
        prop: "label"
      },{
        label: "发布时间",
        prop: "publishDate",
        formatter(row){
          return (row.publishDate || '').replace('T', ' ').substr(0, 19);
        }
      },{
        label: "发布",
        prop: "publishStatus",
        template: true
      }],
      forms:{
        formsType: '',
        formTypeTitle: {
          'ADD': '添加新闻',
          'EDIT': '编辑新闻',
          'VIEW': '查看新闻'
        },
        formModel:{
          title: '',
          author: '',
          label: '',
          content: '',
          attachmentId: '',
          coverPage: ''
        },
        currentForm: null,
        showForm: false,
        formAttrs:{
          labelWidth: '100px',
          rules: {
            title: [{required: true, message: "请输入新闻标题", trigger: "blur"}],
            author: [{required: true, message: "请选择新闻作者", trigger: "change"}],
            content: [{required: true, message: "请输入新闻正文", trigger: "change"}],
            coverPage: [{required: true, message: "请选择新闻缩略图", trigger: "change"}]
          }
        }
      },
      watchDetails:{
        show: false,
        content: ''
      },
    }
  },
  methods:{
    resetForm(){
      Object.keys(this.forms.formModel).map(key => {
        this.forms.formModel[key] = this.forms.currentForm ? this.forms.currentForm[key] : '';
      })
      this.$set(this.forms.formModel, 'label', this.forms.formModel.label ?
          this.forms.formModel.label.split(',') : []);
    },
    addNews(){
      this.forms.formsType = 'ADD';
      this.forms.currentForm = null;
      this.resetForm();
      this.forms.showForm = true;
    },
    search(jumpToFirst){
      this.$refs['table'].loadData(this.model, jumpToFirst);
    },
    editNews(row){
      this.forms.formsType = 'EDIT';
      this.forms.currentForm = row;
      this.resetForm();
      this.forms.showForm = true;
    },
    viewNews(row){
      this.forms.formsType = 'VIEW';
      this.forms.currentForm = row;
      this.resetForm();
      this.forms.showForm = true;
    },
    delNews(row){
      this.$yAxios({
        url: this.$api.applet.removeNews,
        data:{
          ids: [row.id]
        }
      }, info => {
        this.$message({
          type: 'success',
          message: '删除成功'
        });
        this.search();
      })
    },
    post(row){
      this.$yAxios({
        url: this.$api.applet.publishNews,
        data:{
          id: row.id,
          publishStatus: 1,
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: `成功发布新闻【${row.title}】`
        });
        this.search()
      });
    },
    unPost(row){
      this.$yAxios({
        url: this.$api.applet.publishNews,
        data:{
          id: row.id,
          publishStatus: 0,
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: `成功取消发布新闻【${row.title}】`
        });
        this.search()
      });
    },
    ensureModel(form){
      let newForm;
      if(this.forms.formsType === 'EDIT'){
        newForm = Object.assign({}, this.forms.currentForm, form);
      }else{
        newForm = Object.assign({ publishStatus: 0 }, form);
      }
      newForm.label = newForm.label.toString();
      this.$yAxios({
        url: this.$api.applet.saveNews,
        data: newForm
      }, info => {
        this.$message({
          type: 'success',
          message: '保存成功'
        });
        this.search(this.forms.formsType === 'ADD');
      })
    },
    showDetails(row){
      if(row.content){
        this.watchDetails.content = row.content;
        this.watchDetails.show = true;
      }else{
        this.$message({
          type: 'danger',
          message: `该数据无正文`
        });
      }
    },
    updateModel({type, file}){
      switch(type) {
        case 'delete': {
          this.forms.formModel.attachmentId = '';
          this.forms.formModel.coverPage = '';
          break;
        }
        case 'edit': case 'add':{
          this.forms.formModel.attachmentId = file.id;
          this.forms.formModel.coverPage = file.name;
          this.$refs['yForm'].$refs['form'].validateField('coverPage');
          break;
        }
      }
    },
  }
}
</script>

<style scoped lang="less">
.newsList{
  /*@media screen and (max-width: 1919px) {
    .SearchBlock{
      /deep/ .el-form-item{
        &:nth-child(2n+1){
          width: 38%;
        }
        &:nth-child(2n){
          width: calc(62% - 20px);
        }
        .el-form-item__content{
          margin-bottom: 10px;
          .el-input__inner{
            min-width: 220px;
          }
          .el-range-editor{
            min-width: 380px;
          }
        }
      }
      /deep/ .search-buttons{
        >.el-button{
          margin: 0 5px 10px;
        }
      }
      &+*{
        margin-top: -10px;
      }
    }
  }*/
}
</style>